`
https://leetcode.cn/problems/sell-diminishing-valued-colored-balls/
`

/**
 * @param {number[]} inventory
 * @param {number} orders
 * @return {number}
 */
var maxProfit = function (inventory, orders) {
  // 思路：https://leetcode.cn/problems/sell-diminishing-valued-colored-balls/solutions/477204/xiao-shou-jie-zhi-jian-shao-de-yan-se-qiu-by-zerot/
  const MOD = 1e9 + 7

  // 二分找 T
  let left = 0, right = Math.max(...inventory), T = -1
  while (left <= right) {
    const mid = left + Math.floor((right - left) / 2)
    const total = inventory.reduce((acc, cur) => cur >= mid ? acc + cur - mid : acc, 0)
    if (total <= orders) {
      T = mid
      right = mid - 1
    } else {
      left = mid + 1
    }
  }

  const rangeSum = (x, y) => {
    const n = y - x + 1
    return Number((BigInt(x + y) * BigInt(n) / 2n) % BigInt(MOD))
  }

  let rest = orders - inventory.reduce((acc, cur) => cur >= T ? acc + cur - T : acc, 0)
  let res = 0
  for (const ai of inventory) {
    if (ai >= T) {
      if (rest > 0) {
        res += rangeSum(T, ai) % MOD
        rest -= 1
      } else {
        res += rangeSum(T + 1, ai) % MOD
      }
    }
  }

  return res % MOD
};